#!/bin/bash

# mysql download directory
mysql_source=$1

# mysql install directory
mysql_prefix=$2

if [ ! -d "${mysql_source}" ]; then
        echo ">>Failed: mysql_source directory is not exist, create it and execute. "
        exit 1
fi

if [ ! -d "${mysql_prefix}" ]; then
        echo ">>Failed: directory of installing mysql is not exist, create it and execute."
        exit 1
fi

## remove mariadb if system has;
old_mysql=$(rpm -qa|grep -i mysql)

if [ -z "$old_mysql" ];then
	echo ">>Continue: MySQL is not installed on your system."
else
	echo ">>Failed: MySQL has been installed on your system."
	return
fi


old_mariadb=$(rpm -qa|grep -i mariadb)

if [ -z "$old_mariadb" ];then
	echo ">>Continue: Mariadb is not installed on your system."
else
	echo ">>Failed: Mariadb has ben installed on your system, please remove it."
	return
fi


echo ">>Continue: download mysql ..."


mysql_url="https://downloads.mysql.com/archives/get/p/23/file/mysql-5.7.34-1.el7.x86_64.rpm-bundle.tar"

cd ${mysql_source} ##&& wget ${mysql_url}

echo ">>Succed: donload mysql success."

mysql_name=$(echo $mysql_url|awk -F '/' '{print $NF}')

tar -xf ${mysql_name}

common=$(ls mysql-community* | grep mysql-community-common)
rpm -ivh ${common} 

libs=$(ls mysql-community* | grep "mysql-community-libs-[0-9]\+")
rpm -ivh ${libs}

clients=$(ls mysql-community* | grep mysql-community-client)
rpm -ivh ${clients}

yum install -y numactl
yum install -y libaio
server=$(ls mysql-community* | grep mysql-community-server)
rpm -ivh ${server}

if [ $? -eq "0" ];then
	echo ">>Succeed: mysql install success."
else
	echo ">>Failed: mysql installl fail."
fi

password=$(tail -10 /var/log/mysqld.log |grep "temporary password"| awk '{print $NF}') 

echo ">>Imortant: your database password is \"${password}\" ,please change it."

## No check with fllow code.

systemctl start mysqld

mysql -uroot -p"${password}" -e "select version();"

if [ $? -eq "0" ];then
	echo ">>Succeed: mysql has started successfully."
else
	echo ">>Failed: mysql start Failed, Check it please."
	return 
fi

password="Nebula@2021"
mysql -uroot -p"${password}" -e "alter user 'root'@'localhost' by '$password';"

mysql -uroot -p"${password}" -e "select version();"

if [ $? -eq "0" ];then
	echo ">>Succeed: alter password successfully."
else
	echo ">>Failed: alter password Fail, check it now please."
	return
fi

mysql -uroot -p"${password}" -e "create user 'nebula'@'%' identified by '${password}'"
mysql -uroot -p"${password}" -e "grant all privileges on *.* to 'nebula'@'%';"

if [ $? -eq "0" ];then
        echo ">>Succeed: add user:nebula successfully."
else
        echo ">>Failed: add user:nebula fail, check it now please."
        return
fi



